<template>
    <div class="layout01-main">
        <div class="move-box">
            <RiskLeftModule
                v-model="leftSearch"
                :treeData="treeData"
                :leftHeight="leftHeight"
                @on-submit="() => {}"
                @on-handleNode="clickLeftNode"
                :default-expanded-keys="['2']"
                :default-checked-keys="['2']"
                :currentKey="'2'"
                placeholders="编号/名称"
            >
                <template slot="ltitle">动态维度组信息</template>
            </RiskLeftModule>
            <!--  本地、外部  -->
            <template v-if="['1', '2'].includes(leftSelected.id)">
                <RiskRightModule02>
                    <p slot="rtitle">动态维度信息</p>
                    <span slot="button" class="layout01-r-slot">
                        <el-input
                            placeholder="编码/名称/外部编码"
                            v-model="searchData.textTemp"
                            style="width: 170px; margin-right: 10px"
                            size="small"
                            key="table2-input1"
                            clearable
                        />
                        <el-select
                            v-show="leftSelected.id === '2'"
                            v-model="searchData.typeTemp"
                            placeholder="来源类型"
                            style="width: 110px"
                            size="small"
                            key="table1-input2"
                            clearable
                        >
                            <el-option value="2" label="恒生-主动" />
                            <el-option value="5" label="恒生-被动" />
                        </el-select>
                        <el-button
                            type="primary"
                            @click="onSearchMenu(leftSelected.id)"
                            v-authCode.show="B_0011"
                            size="mini"
                            style="margin-left: 10px"
                            key="table1-btn1"
                            >查询</el-button
                        >
                          <el-button
                              type="primary"
                              @click="exportExcel"
                              size="mini"
                              style="margin-left: 10px"
                          >导出</el-button
                          >
                        <el-button
                            type="primary"
                            v-show="leftSelected.id !== '2'"
                            v-authCode.show="B_0008"
                            size="mini"
                            @click="openDynamicGroupDialog('add', null)"
                            key="table1-btn2"
                            >新增</el-button
                        >
                        <el-button type="danger" v-authCode.show="B_0009" @click="openDelModal(undefined)" size="mini" key="table1-btn3"
                            >删除</el-button
                        >
                    </span>
                    <slot>
                        <el-table
                            :data="getComputedTableData.data"
                            border
                            size="mini"
                            v-loading="rightLoading"
                            v-table-top="paging.currentPage"
                            @sort-change="handleTableSort1"
                            :key="tableKey"
                            style="width: 100%"
                            height="calc(100vh - 140px)"
                        >
                            <RiskTableSelection
                                row-key="id"
                                :current-page-table-list="getComputedTableData.data"
                                :selected="selectedList"
                                show-drop-down
                                @dropdown-click="dropdownClick"
                            />
                            <el-table-column prop="dynamicCode" label="维度代码" sortable="custom" width="120"> </el-table-column>
                            <el-table-column prop="dynamicName" label="维度名称" sortable="custom" show-overflow-tooltip> </el-table-column>
                            <el-table-column prop="createUser" label="创建者" sortable="custom" width="120" show-overflow-tooltip> </el-table-column>
                            <el-table-column prop="sourceType" label="来源类型" width="120" sortable="custom" show-overflow-tooltip>
                                <template slot-scope="scope">
                                    {{ DictionConstUtil.SourceType[scope.row.sourceType] }}
                                </template>
                            </el-table-column>
                            <el-table-column prop="sourceCode" label="外部编码" sortable="custom" width="120" show-overflow-tooltip>
                            </el-table-column>

                            <el-table-column label="操作" width="155">
                                <template slot-scope="scope">
                                    <RiskIconButton
                                        type="primary"
                                        icon="el-icon-view"
                                        @on-click="openDynamicGroupDialog('look', scope.row)"
                                        v-authCode.show="B_0012"
                                        topTitle="查看动态维度"
                                    ></RiskIconButton>
                                    <RiskIconButton
                                        type="primary"
                                        icon="el-icon-edit"
                                        @on-click="openDynamicGroupDialog('edit', scope.row)"
                                        v-authCode.show="B_0010"
                                        topTitle="修改动态维度"
                                    ></RiskIconButton>
                                    <RiskIconButton
                                        type="danger"
                                        icon="el-icon-delete"
                                        topTitle="删除动态维度"
                                        v-authCode.show="B_0009"
                                        @on-click="openDelModal(scope.row.id)"
                                    ></RiskIconButton>
                                </template>
                            </el-table-column>
                        </el-table>
                        <div class="block">
                            <risk-pagination :paging="paging" @page-change="currentChange"></risk-pagination>
                        </div>
                    </slot>
                </RiskRightModule02>
                <!-- 删除 -->
                <div>
                    <yh-dialog drag title="确定删除动态维度？" :visible.sync="delVisible" width="500px" :close-on-click-modal="false">
                        <div class="remove-text">
                            <span> {{ delList.join(' , ') }}</span>
                        </div>
                        <div slot="footer" class="dialog-footer">
                            <el-button size="mini" @click="delVisible = false">取 消</el-button>
                            <el-button size="mini" type="primary" @click="delSubmit" v-loading="delLoading">确 定</el-button>
                        </div>
                    </yh-dialog>
                </div>
            </template>
            <template v-else>
                <RiskRightModule02>
                    <p slot="rtitle">证券信息</p>
                    <span slot="button" class="layout01-r-slot">
                        <el-button type="primary" size="mini" v-authCode.show="B_0013" @click="openStockSearchModal" key="table2-btn1"
                            >查询</el-button
                        >
                        <el-button type="primary" size="mini" v-authCode.show="B_0013" @click="refreshTable02" key="table2-btn2">刷新</el-button>
                        <el-button
                            type="primary"
                            size="mini"
                            v-authCode.show="B_0012"
                            @click="openDynamicGroupDialog('look', leftSelected)"
                            key="table2-btn3"
                            >查看</el-button
                        >
                        <el-button
                            type="primary"
                            size="mini"
                            v-authCode.show="B_0010"
                            @click="openDynamicGroupDialog('edit', leftSelected)"
                            key="table2-btn4"
                            >修改</el-button
                        >
                          <el-button
                              type="primary"
                              @click="exportExcel2"
                              size="mini"
                              style="margin-left: 10px"
                          >导出明细</el-button
                          >
                    </span>
                    <slot>
                        <el-table
                            :data="getComputedTableData02"
                            @sort-change="handleTableSort2"
                            v-table-top="paging.currentPage"
                            v-loading="rightLoading"
                            border
                            size="mini"
                            style="width: 100%"
                            height="calc(100vh - 140px)"
                            :key="tableKey"
                        >

                            <RiskTableSelection
                                row-key="stockCode"
                                :current-page-table-list="getComputedTableData02"
                                :selected="selectedList2"
                            />
                            <el-table-column prop="stockCode" label="证券代码" sortable="custom" width="150" show-overflow-tooltip> </el-table-column>
                            <el-table-column prop="reportCode" label="申报代码" sortable="custom" width="150" show-overflow-tooltip>
                            </el-table-column>
                            <el-table-column prop="productCode" label="产品对外代码" sortable="custom" width="150" show-overflow-tooltip>
                            </el-table-column>
                            <el-table-column prop="stockNameSt" label="证券名称" sortable="custom" show-overflow-tooltip></el-table-column>
                            <el-table-column prop="stockType" label="证券类型" sortable="custom" width="120" show-overflow-tooltip>
                                <template slot-scope="scope">
                                    <span>{{ StockTypePojo[scope.row.stockType] }}</span>
                                </template>
                            </el-table-column>
                            <el-table-column prop="marketCode" label="交易市场" sortable="custom" width="120" show-overflow-tooltip>
                                <template slot-scope="scope">
                                    <span>{{ MarketTypePojo[scope.row.marketCode] }}</span>
                                </template>
                            </el-table-column>
                        </el-table>
                        <div class="block">
                            <risk-pagination :paging="paging" @page-change="currentChange"></risk-pagination>
                        </div>
                    </slot>
                </RiskRightModule02>
            </template>
        </div>
        <yh-dialog
            :title="dynamicGroupEditDialog.title"
            :visible.sync="dynamicGroupEditDialog.visible"
            width="800px"
            :close-on-click-modal="false"
            drag
        >
            <div>
                <p style="margin-bottom: 5px">
                    维度名称：
                    <el-input v-model="dynamicGroupEditDialog.dynamicBoundPO.dynamicName" size="mini" style="width: 685px" />
                </p>
                <p style="margin-bottom: 5px">
                    <span>
                        维度代码：
                        <el-input v-model="dynamicGroupEditDialog.dynamicBoundPO.dynamicCode" size="mini" style="width: 150px" disabled />
                    </span>
                    <span>
                        来源类型：
                        <el-select v-model="dynamicGroupEditDialog.dynamicBoundPO.sourceType" size="mini" style="width: 150px">
                            <el-option v-show="dynamicGroupEditDialog.dynamicBoundPO.sourceType === '1'" value="1" label="本地" />
                            <el-option v-show="dynamicGroupEditDialog.dynamicBoundPO.sourceType !== '1'" value="2" label="恒生-主动" />
                            <el-option v-show="dynamicGroupEditDialog.dynamicBoundPO.sourceType !== '1'" value="5" label="恒生-被动" />
                        </el-select>
                    </span>
                    <span v-show="dynamicGroupEditDialog.dynamicBoundPO.sourceType !== '1'">
                        外部代码：
                        <el-input v-model="dynamicGroupEditDialog.dynamicBoundPO.sourceCode" size="mini" style="width: 150px" />
                    </span>
                </p>
            </div>
            <BoundCfg0
                :stockBound="stockBound"
                investGroupType="3"
                :operateType="dynamicGroupEditDialog.type"
                operatePanelHeight="40vh"
                @onHandleOperateOver="onHandleOperateOver"
                @showSearchStockModal="showSearchStockModal"
                :notShowSingleControl="false"
                v-if="dynamicGroupEditDialog.visible"
            />
            <div slot="footer" class="dialog-footer" style="text-align: right; padding-right: 10px">
                <el-button size="mini" @click="dynamicGroupEditDialog.visible = false"> 取 消 </el-button>
                <el-button
                    size="mini"
                    type="primary"
                    @click="dynamicGroupOnSubmit(dynamicGroupEditDialog.type)"
                    v-loading="dynamicGroupEditDialog.loading"
                    v-show="dynamicGroupEditDialog.type != 'look'"
                    >确 定
                </el-button>
            </div>
        </yh-dialog>
        <!--  证券信息查询  -->
        <yh-dialog
            title="证券信息"
            :visible.sync="stockSearchData.visible"
            width="600px"
            :close-on-click-modal="false"
            :before-close="closeModal"
            drag
        >
            <div>
                <el-row :gutter="10">
                    <el-col :span="3"><span>证券代码: </span></el-col>
                    <el-col :span="9"> <el-input v-model="stockSearchData.stockCode" placeholder="证券代码" clearable size="mini"></el-input></el-col>
                    <el-col :span="3"><span>证券名称: </span></el-col>
                    <el-col :span="9">
                        <el-input v-model="stockSearchData.stockNameSt" placeholder="证券名称" clearable size="mini"></el-input
                    ></el-col>
                </el-row>
                <el-row :gutter="10" style="margin-top: 5px">
                    <el-col :span="3"><span>证券类型: </span></el-col>
                    <el-col :span="9">
                        <el-select v-model="stockSearchData.stockTypes" placeholder="证券类型" size="mini" clearable filterable>
                            <el-option v-for="(sLabel, sKey) in StockTypePojo" :label="`${sKey} ${sLabel}`" :value="sKey" :key="sKey" />
                        </el-select>
                    </el-col>
                    <el-col :span="3"><span>市场类型: </span></el-col>
                    <el-col :span="9">
                        <el-select v-model="stockSearchData.marketCodes" placeholder="市场类型" size="mini" clearable filterable>
                            <el-option v-for="(mLabel, mKey) in MarketTypePojo" :label="`${mKey} ${mLabel}`" :value="mKey" :key="mKey" />
                        </el-select>
                    </el-col>
                </el-row>
                <div style="margin-top: 5px; text-align: right">
                    <el-button size="mini" @click="openStockSearchModal">重 置</el-button>
                    <el-button size="mini" type="primary" @click="getStockDataSourceList(1)">搜 索</el-button>
                </div>
                <el-table
                    :data="stockSearchData.dataSource"
                    v-table-top="stockSearchData.paging.currentPage"
                    @row-dblclick="stockSearchSubmit"
                    v-loading="stockSearchLoading"
                    style="width: 100%;margin-top:6px"
                    height="250px"
                    size="mini"
                    border
                >
                    <el-table-column prop="stockCode" label="证券代码" width="150" show-overflow-tooltip> </el-table-column>
                    <el-table-column prop="stockNameSt" label="证券名称" show-overflow-tooltip> </el-table-column>
                    <el-table-column prop="stockTypeText" label="证券类型" width="150" show-overflow-tooltip> </el-table-column>
                    <el-table-column prop="marketCodeText" label="市场类型" show-overflow-tooltip></el-table-column>
                </el-table>
                <div class="block">
                    <risk-pagination :paging="stockSearchData.paging" @page-change="getStockDataSourceList"></risk-pagination>
                </div>
            </div>
        </yh-dialog>
        <!-- 比对差异 -->
        <yh-dialog
            title="确认提交更新吗"
            :visible.sync="verification"
            width="600px"
            top="25vh"
            drag
            :close-on-click-modal="false"
            :close-on-press-escape="false"
        >
            <div>
                <EntryItemCompare
                    v-if="compareDiffData.DynamicBoundPO && compareDiffData.DynamicBoundPO.length > 0"
                    title="动态维度基本信息"
                    :data="compareDiffData.DynamicBoundPO"
                />
                <EntryItemCompare
                    v-if="compareDiffData.DynamicOriginalBoundConfigPO && compareDiffData.DynamicOriginalBoundConfigPO.length > 0"
                    title="动态维度范围信息"
                    :data="compareDiffData.DynamicOriginalBoundConfigPO"
                />
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button size="mini" @click="verification = false">取 消</el-button>
                <el-button size="mini" :disabled="sbmitdisabled" type="primary" @click="submitData">确 定 </el-button>
            </div>
        </yh-dialog>
    </div>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator';
import { getCurrentPageData } from '@/utils/tools';
import DictionConstUtil from '@/utils/diction-const-util';
import * as XLSX from 'xlsx';
import { Loading } from 'element-ui';
import {
    deleteDynamicBound,
    getDynamicBoundList,
    getDynamicStockList,
    IDynamic,
    originalStockList,
    updateDynamicBound,
    addDynamicBound,
    getDynamicBoundConfig,
} from '@/pages/setting/api';

import RiskLeftModule from '@/common/components/risk-left-module.vue';
import RiskRightModule02 from '@/common/components/risk-right-module02.vue';
import RiskIconButton from '@/common/components/risk-icon-button.vue';
import RiskTrantable from '@/common/components/risk-trantable.vue';
import BoundCfg0 from '../baseparam/fund-group-setting/BoundCfg0.vue';
import RiskPagination from '@/common/components/risk-pagination.vue';
import EntryItemCompare from './components/item-setting/item-compare.vue';

export interface pages {
    total?: number;
    pageSize?: number;
    currentPage?: number;
}

@Component({
    name: 'DynamicSetting',
    components: {
        RiskLeftModule,
        RiskRightModule02,
        RiskIconButton,
        RiskTrantable,
        BoundCfg0,
        RiskPagination,
        EntryItemCompare,
    },
})
export default class DynamicSetting extends Vue {
    async mounted() {
        DictionConstUtil.FNMarketType().then(result => {
            this.$set(this, 'MarketTypePojo', DictionConstUtil.ListToPojo(result));
        });
        DictionConstUtil.FNStockType().then(result => {
            this.$set(this, 'StockTypePojo', DictionConstUtil.ListToPojo(result));
        });
        await this.getLeftData();
        this.getRightTableData();
    }

    private DictionConstUtil = DictionConstUtil;
    private StockTypePojo: any = {};
    private MarketTypePojo: any = {};

    /**
     * ----- 左侧功能 start -----
     */
    private leftLoading = false;
    private leftSearch: string = '';
    private leftHeight: string = '100vh';
    private treeData = [
        {
            label: '本地',
            id: '1',
            sourceType: '1',
            children: [] as IDynamic[],
        },
        {
            label: '外部',
            id: '2',
            sourceType: '2',
            children: [] as IDynamic[],
        },
    ];
    private leftSelected: IDynamic = { label: '外部', id: '2', sourceType: '2' };

    sort: any = {}; // 动态维度排序字段
    sortParam1: string = ''; // 证券信息排序字段
    tableKey: number = 0;

    // 获取左边数据
    getLeftData() {
        this.leftLoading = true;
        return getDynamicBoundList()
            .then(res => {
                res.sort((a, b) => (b as any).dynamicCode.replace(/[^0-9]/gi, '') - (a as any).dynamicCode.replace(/[^0-9]/gi, '')).forEach(item => {
                    item.id = item.dynamicCode;
                    item.label = item.dynamicCode + '-' + item.dynamicName;
                });
                const local = res.filter(item => item.sourceType === '1');
                const outside = res.filter(item => item.sourceType !== '1');
                this.$set(this.treeData[0], 'children', local);
                this.$set(this.treeData[1], 'children', outside);
            })
            .finally(() => {
                this.leftLoading = false;
            });
    }

    /**
     *  左边选择节点
     *  @param data 节点数据
     */
    clickLeftNode(data) {
        if (data.id === this.leftSelected.id) return;
        this.dbClickStockCode = null;
        this.leftSelected = { ...data };
        this.paging.currentPage = 1;
        this.sortParam1 = '';
        this.tableKey++;

        // 清理工作
        this.selectedList = [];
        this.selectedList2 = [];
        this.tableData2 = [];
        this.searchData = {
            textTemp: '',
            text: '',
            typeTemp: '',
            type: '',
        };
        this.tableData = [];

        this.getRightTableData();
    }
    /**
     * ----- 左侧功能 end -----
     */

    /**
     * ----- 右侧功能 start -----
     */
    private rightLoading = false;
    private tableData: any[] = [];
    private tableData2 = [];
    private selectedList: string[] = [];
    private selectedList2: string[] = [];
    /** 动态维度选中的表数据 */
    public multipleSelection = [];
    /** 证券明细选中的表数据 */
    public multipleSelection2 = [];
    public loading: any = null;
    dbClickStockCode: any = null; // 查询条件双击行

    private searchData = {
        textTemp: '',
        text: '',
        typeTemp: '',
        type: '',
    };
    private paging: pages = {
        total: 0,
        currentPage: 1,
        pageSize: 50,
    };

    // 排序参数
    sortParamObj1 = {
        stockCode: 'C_STOCK_CODE',
        reportCode: 'C_REPORT_CODE',
        productCode: 'C_PRODUCT_CODE',
        stockNameSt: 'C_STOCK_NAME_ST',
        stockType: 'C_STOCK_TYPE',
        marketCode: 'C_MARKET_CODE',
    };

    // private searchStockParam: any = {
    //     marketCodes: '',
    //     stockTypes: '',
    // };

    // 自动计算表格数据 - 动态维度信息
    private get getComputedTableData(): any {
        let data: any = [];
        let { text, type } = this.searchData;
        let tempArr = this.tableData.filter(item => {
            if (!text) {
                return true;
            } else {
                let label = `${item.dynamicCode}_${item.dynamicName}_${item.sourceCode}`;
                return label.indexOf(text) > -1;
            }
        });

        text = text.trim();

        if (this.leftSelected.id === '2') {
            // 外部
            tempArr = tempArr.filter(item => {
                if (!type) {
                    return true;
                } else {
                    return type === item.sourceType;
                }
            });
        }

        if (['1', '2'].includes(this.leftSelected.id)) {
            if (this.sort?.type) {
                data = tempArr.slice().sort(this.compare(this.sort.prop, this.sort.type));
            } else {
                data = tempArr;
            }
            this.paging.total = tempArr.length;
            return {
                allData: data,
                data: getCurrentPageData(data, this.paging.currentPage, this.paging.pageSize),
                total: tempArr.length,
            };
        }

        // this.paging.total = tempArr.length;
        // return {
        //     allData: tempArr,
        //     data: getCurrentPageData(tempArr, this.paging.currentPage, this.paging.pageSize),
        //     total: tempArr.length,
        // };
    }

    /**
     * 比较函数
     * @param  {string} prop 数据里面要排序的key
     * @param  {number} type 1:asc  -1:desc
     * @return {number}
     */
    private compare(prop, type) {
        return function(obj1, obj2) {
            if (type == '1') {
                return obj1[prop].localeCompare(obj2[prop], 'zh-CN', { numeric: true });
            } else if (type == '-1') {
                return obj2[prop].localeCompare(obj1[prop], 'zh-CN', { numeric: true });
            }
        };
    }

    // 自动计算表格数据 - 证券信息
    private get getComputedTableData02(): any[] {
        return this.tableData;
    }

    closeModal() {
        this.stockSearchData = {
            dynamicCode: '',
            marketCodes: '',
            paging: {
                total: 0,
                currentPage: 1,
                pageSize: 20,
            },
            stockCode: '',
            stockNameSt: '',
            stockTypes: '',
            visible: false,
            dataSource: [],
        };
    }

    handleTableSort1({ column, prop, order }) {
        if (order) {
            let type = order == 'ascending' ? '1' : order == 'descending' ? '-1' : '';
            this.sort = { prop, type };
        } else {
            this.sort = {};
        }
        this.paging.currentPage = 1;
        this.getRightTableData(this.paging);
    }

    handleTableSort2(column) {
        let sortType = column.order == 'ascending' ? 'ASC' : column.order == 'descending' ? 'DESC' : '';
        if (sortType) {
            this.sortParam1 = this.sortParamObj1[column.prop] + ' ' + sortType;
        } else {
            this.sortParam1 = '';
        }
        this.paging.currentPage = 1;
        this.getRightTableData(this.paging);
    }

    /**
     * 获取右边的数据
     */
    getRightTableData(page?: pages) {
        let leftSelected = this.leftSelected;
        if (['1', '2'].includes(leftSelected.id)) {
            // debugger;
            // 本地或外部
            this.tableData = leftSelected.id === '1' ? this.treeData[0].children : this.treeData[1].children;
            const paging = page || this.paging;
            paging.total = this.tableData.length;
            this.paging = paging;
        } else {
            // 子项
            const paging = page || { ...this.paging };
            let data = { dynamicCode: leftSelected.id, paging: this.paging, stockCode: this.dbClickStockCode, sort: this.sortParam1 };
            this.rightLoading = true;
            this.leftLoading = true;
            getDynamicStockList(data)
                .then(async res => {
                    if (JSON.stringify(this.StockTypePojo) === JSON.stringify({})) {
                        try {
                            const FNStockType = await DictionConstUtil.FNStockType();
                            const StockTypePojo = DictionConstUtil.ListToPojo(FNStockType);
                            this.$set(this, 'StockTypePojo', StockTypePojo);
                        } catch (e) {}
                    }
                    if (JSON.stringify(this.MarketTypePojo) === JSON.stringify({})) {
                        try {
                            const FNMarketType = await DictionConstUtil.FNMarketType();
                            const MarketTypePojo = DictionConstUtil.ListToPojo(FNMarketType);
                            this.$set(this, 'MarketTypePojo', MarketTypePojo);
                        } catch (e) {}
                    }
                    // res.list.forEach(item => {
                    //     item.stockTypeText = this.StockTypePojo[item.stockType];
                    //     item.marketCodeText = this.MarketTypePojo[item.marketCode];
                    // });
                    this.paging.total = res.total;
                    if (res && res.list) {
                        this.tableData = res.list;
                        this.tableData2 = this.tableData2.concat(this.tableData);
                        this.tableData2 = Array.from(new Set(this.tableData2.map(item => JSON.stringify(item)))).map(item => JSON.parse(item));
                    } else {
                        this.tableData = [];
                    }
                    this.rightLoading = false;
                    this.leftLoading = false;
                })
                .catch(() => {
                    this.rightLoading = false;
                    this.leftLoading = false;
                });
        }
    }

    /**
     * 搜索动态维度信息
     */
    onSearchMenu(id) {
        this.searchData.text = this.searchData.textTemp;
        this.searchData.type = this.searchData.typeTemp;
    }

    /**
     * 动态维度导出excel
     */
    exportExcel() {
        if (this.selectedList.length == 0 && this.getComputedTableData.allData.length > 0) {
          //  this.multipleSelection = this.getComputedTableData.allData;
            this.multipleSelection = this.getComputedTableData.allData.map(item => Object.assign({}, item, { sourceType: DictionConstUtil.SourceType[item.sourceType] }));
            this.$confirm('此操作将导出所有数据共' + this.multipleSelection.length + '条, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            })
                .then(() => {
                    this.dataExport(this.multipleSelection);
                })
                .catch(() => {
                    this.yh_message_info('已取消操作');
            });
        } else if (this.selectedList.length > 0) {
            const filter = this.getComputedTableData.allData.filter(item => this.selectedList.includes(item.id));
            this.multipleSelection = filter.map(item => Object.assign({}, item, { sourceType: DictionConstUtil.SourceType[item.sourceType] }));
            this.$confirm('此操作将导出你选中的数据共' + filter.length + '条, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            })
                .then(() => {
                    this.dataExport(this.multipleSelection);
                })
                .catch(() => {
                    this.yh_message_info('已取消操作');
                });
        } else {
            this.yh_message_warn('当前页面无数据可导出!');
        }
    }

    /**
     * 明细导出excel
     */
    exportExcel2() {
        if (this.selectedList2.length == 0 && this.tableData2.length > 0) {
            this.$confirm('此操作将导出所有数据共' + this.paging.total + '条, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            })
                .then(() => {
                    this.rightLoading = true;
                    this.leftLoading = true;
                    let data = { dynamicCode: this.leftSelected.id, paging: {total: 0, currentPage: 1, pageSize: this.paging.total}, stockCode: this.dbClickStockCode, sort: this.sortParam1 };
                    getDynamicStockList(data)
                        .then(async res => {
                            if (res && res.list) {
                                this.multipleSelection = res.list;
                                this.dataExport2(this.multipleSelection);
                                this.rightLoading = false;
                                this.leftLoading = false;
                            } else {
                                this.yh_message_info('导出失败');
                                this.rightLoading = false;
                                this.leftLoading = false;
                            }
                        }).catch(() => {
                        this.rightLoading = false;
                        this.leftLoading = false;
                    });
                })
                .catch(() => {
                    this.yh_message_info('已取消操作');
                });
        } else if (this.selectedList2.length > 0) {
            const filter = this.tableData2.filter(item => this.selectedList2.includes(item.stockCode));
            this.multipleSelection2 = filter;
            this.$confirm('此操作将导出你选中的数据共' + filter.length + '条, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            })
                .then(() => {
                    this.dataExport2(this.multipleSelection2);
                })
                .catch(() => {
                    this.yh_message_info('已取消操作');
                });
        } else {
            this.yh_message_warn('当前页面无数据可导出!');
        }
    }

    /** 执行数据导出 */
    public dataExport(multipleSelection) {
        this.loading = Loading.service({
            text: '处理中...',
            background: 'rgba(0,0,0,.5)'
        })
        let arr = multipleSelection.map(item => {
            return {
                维度代码: item.dynamicCode,
                维度名称: item.dynamicName,
                创建者: item.createUser,
                来源类型: item.sourceType,
                外部编码: item.sourceCode
            }
        })
        const data = [
            { Name: 'Alice', Age: 25 },
            { Name: 'Bob', Age: 30 }
        ];
     //   const header = ['维度代码', '维度名称', '创建者', '来源类型', '外部编码'];
      //  const sheet = XLSX.utils.json_to_sheet(arr, { header: header });
        let sheet = XLSX.utils.json_to_sheet(arr);
            let book = XLSX.utils.book_new()

        // 设置表头样式
        const headerStyle = {
            font: { bold: true, color: { rgb: 'FF0000' } }, // 设置粗体和红色字体
            fill: { fgColor: { rgb: 'FFFF00' } } // 设置背景颜色为黄色
        };
        sheet['!cols'] = [{ wch: 20 }, { wch: 20 }, { wch: 20 }, { wch: 20 }, { wch: 20 }]; // 设置列宽

        // 将样式应用到表头
        sheet['A1'].s = headerStyle;
        sheet['B1'].s = headerStyle;
        sheet['C1'].s = headerStyle;
        XLSX.utils.book_append_sheet(book, sheet, '动态维度信息')
        XLSX.writeFile(book, `动态维度${this.dateToString(new Date())}.xlsx`) // 文件名
        this.loading.close()
    }

    /** 维度明细数据导出 */
    public dataExport2(multipleSelection) {
        this.loading = Loading.service({
            text: '处理中...',
            background: 'rgba(0,0,0,.5)'
        })
        let arr = multipleSelection.map(item => {
            return {
                证券代码: item.stockCode,
                申报代码: item.reportCode,
                产品对外代码: item.productCode,
                证券名称: item.stockNameSt,
                证券类型: this.StockTypePojo[item.stockType],
                交易市场: this.MarketTypePojo[item.marketCode]
            }
        })
        const data = [
            { Name: 'Alice', Age: 25 },
            { Name: 'Bob', Age: 30 }
        ];
        //   const header = ['维度代码', '维度名称', '创建者', '来源类型', '外部编码'];
        //  const sheet = XLSX.utils.json_to_sheet(arr, { header: header });
        let sheet = XLSX.utils.json_to_sheet(arr);
        let book = XLSX.utils.book_new()

        // 设置表头样式
        const headerStyle = {
            font: { bold: true, color: { rgb: 'FF0000' } }, // 设置粗体和红色字体
            fill: { fgColor: { rgb: 'FFFF00' } } // 设置背景颜色为黄色
        };
        sheet['!cols'] = [{ wch: 20 }, { wch: 20 }, { wch: 20 }, { wch: 20 }, { wch: 20 }, { wch: 20 }]; // 设置列宽

        // 将样式应用到表头
        sheet['A1'].s = headerStyle;
        sheet['B1'].s = headerStyle;
        sheet['C1'].s = headerStyle;
        XLSX.utils.book_append_sheet(book, sheet, '证券信息')
        XLSX.writeFile(book, `动态维度${this.leftSelected.label}明细${this.dateToString(new Date())}.xlsx`) // 文件名
        this.loading.close()
    }

    // 日期转字符串
    public dateToString(date) {
        var y = date.getFullYear();
        var m = date.getMonth() + 1;
        m = m < 10 ? ('0' + m) : m;
        var d = date.getDate();
        d = d < 10 ? ('0' + d) : d;
        var h = date.getHours();
        h = h < 10 ? ('0' + h) : h;
        var minute = date.getMinutes();
        minute = minute < 10 ? ('0' + minute) : minute;
        var second = date.getSeconds();
        second = second < 10 ? ('0' + second) : second;
        return y + '-' + m + '-' + d + '_' + h + '-' + minute + '-' + second;
    }

    /**
     *  左边选择节点
     *  @param data 节点数据
     */
    refreshTable02() {
        this.paging.currentPage = 1;
        this.getRightTableData();
    }

    // 全选功能
    dropdownClick(command: string) {
        if (command === 'all') {
            this.selectedList = this.getComputedTableData.allData.map(item => item.id);
        }
    }

    // 翻页功能
    currentChange() {
        let paging = this.paging;
        this.getRightTableData(paging);
    }

    /**
     * ----- 右侧功能 end -----
     */

    /**
     * ----- 弹窗功能 start -----
     */
    private delVisible: boolean = false;
    private delList: string[] = [];
    private delLoading = false;

    // 打开删除弹窗
    openDelModal(key) {
        if (key) {
            this.delList = [key];
        } else {
            if (!this.selectedList.length) {
                this.yh_message_success('未选择动态维度');
                return;
            }
            this.delList = [...this.selectedList];
        }
        this.delVisible = true;
    }

    // 删除功能
    delSubmit() {
        this.delLoading = true;
        deleteDynamicBound(this.delList)
            .then(async () => {
                this.yh_message_success('删除成功');
                // this.$message({
                //     message: '删除成功',
                //     type: 'success',
                //     duration: 1000,
                // });
                this.delVisible = false;
                this.selectedList = [];
                await this.getLeftData();
                this.getRightTableData();
            })
            .finally(() => {
                this.delLoading = false;
            });
    }
    /**
     * ----- 弹窗功能 end -----
     */

    /**
     * ----- 证券详情弹窗功能 start -----
     */
    private stockSearchData = {
        dynamicCode: '',
        marketCodes: '',
        paging: {
            total: 0,
            currentPage: 1,
            pageSize: 20,
        },
        stockCode: '',
        stockNameSt: '',
        stockTypes: '',
        visible: false,
        dataSource: [],
    };
    private stockSearchLoading = false;

    // 证券信息查询弹窗 - 打开证券信息查询弹窗
    openStockSearchModal() {
        this.stockSearchData = {
            dynamicCode: '',
            marketCodes: '',
            paging: {
                total: 0,
                currentPage: 1,
                pageSize: 20,
            },
            stockCode: '',
            stockNameSt: '',
            stockTypes: '',
            visible: true,
            dataSource: [],
        };
        this.getStockDataSourceList();
    }

    // 证券信息查询弹窗 - 获取证券代码列表
    getStockDataSourceList(currentPage?: number) {
        if (currentPage) {
            this.stockSearchData.paging.currentPage = currentPage;
        }
        this.stockSearchLoading = true;
        // let data = {
        //     dynamicCode: this.leftSelected.id,
        //     stockCode: this.stockSearchData.stockCode,
        //     paging: this.stockSearchData.paging,
        //     stockInfoPOS: this.stockSearchData,
        // };
        // getDynamicStockList(data)
        this.stockSearchData.dynamicCode = this.leftSelected.id;
        let data = {
            dynamicCode: this.stockSearchData.dynamicCode,
            marketCodes: this.stockSearchData.marketCodes ? [this.stockSearchData.marketCodes] : [],
            stockTypes: this.stockSearchData.stockTypes ? [this.stockSearchData.stockTypes] : [],
            stockCode: this.stockSearchData.stockCode,
            stockNameSt: this.stockSearchData.stockNameSt,
            paging: this.stockSearchData.paging,
        };
        this.$axios
            .post('/dynamic/stockList/dynamicInfo', data)
            .then((res: any) => {
                let dataSource = res.list || [];
                dataSource.forEach(item => {
                    item.stockTypeText = this.StockTypePojo[item.stockType];
                    item.marketCodeText = this.MarketTypePojo[item.marketCode];
                });
                this.stockSearchData.paging.total = res.total;
                this.stockSearchData.dataSource = dataSource;
            })
            .finally(() => {
                this.stockSearchLoading = false;
            });
    }

    private showSearchStockModal(isShow: boolean): void {
        this.stockSearchData.visible = isShow;
        this.getStockDataSourceList();
    }

    // 双击鼠标搜索
    stockSearchSubmit(row) {
        this.paging.currentPage = 1;
        this.stockSearchData.visible = false;
        this.dbClickStockCode = row.stockCode;
        this.getRightTableData(this.paging);
    }

    /**
     * ----- 证券详情弹窗功能 end -----
     */

    /**
     * ----- 动态维度范围弹窗功能 start -----
     */

    verification: boolean = false;
    before: any = {}; // 编辑和查看获取原数据
    compareDiffData: any[] = [];

    private stockBound = [];

    private dynamicGroupEditDialog = {
        title: '',
        type: '',
        visible: false,
        loading: false,
        dynamicBoundPO: {
            dynamicCode: '',
            dynamicName: '',
            dynamicType: '',
            groupType: '3',
            operatorName: '',
            separateValid: '',
            sourceType: '',
            sourceCode: '',
        },
        stockList: [],
    };
    // 打开范围属性弹窗
    async openDynamicGroupDialog(type, row) {
        let stockList = [];
        if (type === 'add') {
            this.dynamicGroupEditDialog.title = '添加动态维度';
            // this.dynamicGroupEditDialog.stockList = stockList;
            this.stockBound = stockList;
            this.dynamicGroupEditDialog.type = type;
            this.dynamicGroupEditDialog.dynamicBoundPO = {
                dynamicCode: '自动添加',
                dynamicName: '',
                dynamicType: '',
                groupType: '3',
                operatorName: '',
                separateValid: '',
                sourceType: this.leftSelected.sourceType === '1' ? '1' : '2',
                sourceCode: '',
            };
            this.dynamicGroupEditDialog.visible = true;
        } else {
            this.dynamicGroupEditDialog.title = type === 'edit' ? '编辑动态维度' : '查看动态维度';
            stockList = await getDynamicBoundConfig(row.dynamicCode);
            // this.dynamicGroupEditDialog.stockList = stockList;
            this.before['dynamicOriginalBoundConfigPOList'] = stockList;
            this.stockBound = stockList;
            this.dynamicGroupEditDialog.type = type;
            // this.dynamicGroupEditDialog.dynamicBoundPO = {
            //     dynamicCode: row.dynamicCode,
            //     dynamicName: row.dynamicName,
            //     dynamicType: row.dynamicType,
            //     groupType: row.groupType,
            //     operatorName: row.operatorName,
            //     separateValid: row.separateValid,
            //     sourceType: row.sourceType,
            //     sourceCode: row.sourceCode,
            // };
            this.dynamicGroupEditDialog.dynamicBoundPO = { ...row };
            this.before['dynamicBoundPO'] = { ...row };
            this.dynamicGroupEditDialog.visible = true;
        }
    }

    // 修改回调
    onHandleOperateOver(value) {
        this.$set(this.dynamicGroupEditDialog, 'stockList', value);
        // dynamicGroupEditDialog.stockList
    }

    // 提交动态维度
    dynamicGroupOnSubmit(type) {
        const dynamicBoundPO = this.dynamicGroupEditDialog.dynamicBoundPO;
        const dynamicOriginalBoundConfigPOList = this.dynamicGroupEditDialog.stockList;
        if (!dynamicBoundPO.dynamicName) {
            this.yh_message_success('请输入维度名称');
            return;
        }
        if (dynamicBoundPO.sourceType !== '1' && !dynamicBoundPO.sourceCode) {
            this.yh_message_success('请输入外部代码');
            return;
        }
        if (!dynamicOriginalBoundConfigPOList.length) {
            this.yh_message_success('请添加范围配置');
            return;
        }
        if (type === 'edit') {
            this.dynamicGroupEditDialog.loading = true;
            let daats = {
                before: this.before,
                after: { dynamicBoundPO, dynamicOriginalBoundConfigPOList },
            };
            this.$axios
                .post('/dynamic/compare', daats)
                .then((res: any) => {
                    if (JSON.stringify(res) == '{}') {
                        this.yh_message_success('动态维度无修改！');
                    } else {
                        this.compareDiffData = res;
                        this.verification = true;
                    }
                })
                .finally(() => {
                    this.dynamicGroupEditDialog.loading = false;
                });
        } else if (type === 'add') {
            this.dynamicGroupEditDialog.loading = true;
            addDynamicBound({
                dynamicBoundPO,
                dynamicOriginalBoundConfigPOList,
            })
                .then(async res => {
                    this.dynamicGroupEditDialog.visible = false;
                    this.yh_message_success('新增动态维度成功');
                    await this.getLeftData();
                    this.getRightTableData();
                })
                .finally(() => {
                    this.dynamicGroupEditDialog.loading = false;
                });
        }
    }
    // 比较差异"确定"
    submitData() {
        this.verification = false;
        this.dynamicGroupEditDialog.loading = true;
        let dynamicBoundPO = this.dynamicGroupEditDialog.dynamicBoundPO;
        let dynamicOriginalBoundConfigPOList = this.dynamicGroupEditDialog.stockList;
        updateDynamicBound({
            dynamicBoundPO,
            dynamicOriginalBoundConfigPOList,
        })
            .then(async res => {
                this.dynamicGroupEditDialog.visible = false;
                this.yh_message_success('编辑动态维度成功');
                await this.getLeftData();
                this.getRightTableData();
                if (dynamicBoundPO.dynamicCode === this.leftSelected.id) {
                    for (let treeDatum of this.treeData) {
                        let leftSelected = null;
                        for (let child of treeDatum.children) {
                            if (child.id === dynamicBoundPO.dynamicCode) {
                                leftSelected = { ...child };
                                this.leftSelected = leftSelected;
                                break;
                            }
                        }
                        if (leftSelected) break;
                    }
                }
            })
            .finally(() => {
                this.dynamicGroupEditDialog.loading = false;
            });
    }
    /**
     * ----- 动态维度范围弹窗功能 end -----
     */
}
</script>
<style lang="scss" scoped>
@import '../../assets/style/layout01';
</style>
